var roleManageApp = new Vue({
    el: '#roleManageApp',
    data: {
        roleList: [], //  角色列表
        roleTypeList: [], // 角色类型列表
        searchKey: "",  // 角色查询字段
        rolePageFilterParameters: {
            searchKey: "",
        },
        employeePageFilterParameters: {
          searchKey: '',
          current: 1,
          pageSize: 10,
          companyId: -1,
          roleId: -1,
        },
        checkedMembers: [],
        activeRole: {},
        activeRoleEditBtns: {},
        roleMembersPaging: {},
        roleAppList: [],
        roleFunList: [],
        roleEditBtnStatus: {},
        showAddRoleModal: false,
        showAddMemberModal: false,
        showSetRoleAppPermissionModal: false,
        showEditRoleModal: false,
        activeAppPermissionTree: [],
        selectedRoleApp: {},
        permissionIds: [],
        editRoleData: {},
        selectedMembers:[],
        selectedRemoveMembers: [], // 批量移除时选中的成员
        employeeSearchKey: '',
        employees: [],
        // 添加角色
        addRoleData: {
            companyId: -1,
            name: "",
            type: -1,
            description: "",
        }
    },
    mounted:  function(){
        this.getAccountInfo()
        this.initData()
    },
    /**
     * 监控searchKey的变化，查询角色
     */
    watch: {
        searchKey: function() {
            this.getRoleList()
        }
    },
    methods: {
        /**
         * 初始化数据
         */
        initData: function() {
            this.getRoleList()
            this.getRoleTypeList();
            VUE_UTIL.delegate("click", "unFoldBtn", function(event){
                var btn = event.target;
                if(btn.innerHTML == "+") {
                    btn.innerHTML = "-";
                } else {
                    btn.innerHTML = "+";
                }
                var subTreeNode = VUE_UTIL.getChild(btn.parentNode.nextElementSibling, "treeNode");
                VUE_UTIL.toggleElement(subTreeNode);
                VUE_UTIL.hideElement(VUE_UTIL.getChildren())
            })
            VUE_UTIL.delegate("click", "department", function(event){
                var target = event.target;
                var ulChildren = target.querySelectorAll("ul");
                for(var i=0; i<ulChildren.length;i++) {
                    target.removeChild(ulChildren[i])
                }
                var postData = {
                    departmentId: target.getAttribute("data-id"),
                }
                VUE_UTIL.getAxiosInstance().post("/basedata/employee/queryEmployeeJson",VUE_UTIL.buildPostFormData(postData))
                    .then(function(response){
                       var employees = response.data.data
                        var ul = document.createElement("ul");
                       ul.setAttribute("class", "employee-ul")
                        for(var i = 0; i< employees.length; i++){
                            var employee = document.createElement("li")
                            employee.setAttribute("data-id", employees[i].employeeId);
                            employee.setAttribute("class", "employee");
                            employee.innerHTML = employees[i].employeeName;
                            var checkbox = document.createElement("input");
                            checkbox.setAttribute("type", "checkbox");
                            checkbox.setAttribute("class", "employee-checkbox");
                            checkbox.setAttribute("data-id", employees[i].employeeId);
                            checkbox.setAttribute("name", "selectedEmployees");
                            checkbox.setAttribute("data-name", employees[i].employeeName);
                            checkbox.setAttribute("value",employees[i].employeeId);
                            employee.appendChild(checkbox);
                            ul.appendChild(employee);

                        }
                        target.appendChild(ul)
                    })
            })
        },
        /**
         * 获取当前账号信息
         */
        getAccountInfo: function() {
            var requestUrl = VUE_UTIL.buildRequestUrl('/account/queryAccountDetail', {})
            VUE_UTIL.getAxiosInstance().get(requestUrl)
                .then(function(response){
                    if(response.data && response.data.data) {
                        VUE_UTIL.setLocalStorage("userInfo", JSON.stringify(response.data.data))
                    }
                })
        },
        /**
         * 清空搜索关键词
         * @param event
         */
        removeSearchKey: function(event) {
            this.rolePageFilterParameters.searchKey = ''
            this.getRoleList()
        },
        /**
         * 角色列表查询
         * @param event
         */
        search: function(event) {
            this.getRoleList()
        },
        /**
         * 获取角色列表
         */
        getRoleList: _.debounce(
            function(){
                var _self = this
                var requestUrl = VUE_UTIL.buildRequestUrl('/admin/role/queryList', {
                    searchKey: this.rolePageFilterParameters.searchKey
                })
                VUE_UTIL.getAxiosInstance().get(requestUrl)
                    .then(function(response){
                        _self.roleList = response.data.data
                    })
            },
            500
        ),
        /**
         * 获取角色类型列表
         */
        getRoleTypeList: function() {
            var _self = this
            var requestUrl = VUE_UTIL.buildRequestUrl('/admin/role/roleTypeList', {})
            VUE_UTIL.getAxiosInstance().get(requestUrl)
                .then(function(response){
                    _self.roleTypeList = response.data.data
                })
        },
        /**
         * 删除角色
         * @param id
         */
        removeRole: function(id) {
            var _self = this
            var postData = {
                id: id,
                dFlag: 1,
            }
            VUE_UTIL.getAxiosInstance().post("/basedata/employee/delete",VUE_UTIL.buildPostFormData(postData))
            .then(function(response){
                if (response.data.success == true){
                    layer.msg('删除成功', {time: 1000})
                    _self.getRoleList()
                } else {
                    layer.msg('删除失败', {time: 1000})
                }
            })
        },
        /**
         * 设置当前选中角色
         * @param role
         */
        setActiveRole: function(role){
            this.activeRole = role
            this.getRoleMemebers(this.activeRole)
            this.getRoleAppList(this.activeRole)
            this.getRoleFunList(this.activeRole)
            this.activeRoleEditBtns = {}
        },
        /**
         * 显示角色右侧操作列表
         * @param role
         */
        setActiveRoleEditBtns: function(role) {
            if (role == this.activeRoleEditBtns) {
                this.activeRoleEditBtns = {}
            } else {
                this.activeRoleEditBtns = role
            }
        },
        /**
         * 获取角色成员列表
         * @param role
         */
        getRoleMemebers: function(role) {
            var _self = this
            this.employeePageFilterParameters.roleId = role.id
            var requestUrl = VUE_UTIL.buildRequestUrl('/basedata/employee/queryPageList', this.employeePageFilterParameters)
            VUE_UTIL.getAxiosInstance().get(requestUrl)
                .then(function(response){
                    _self.roleMembersPaging = response.data.data
                })

        },
        /**
         * 获取角色应用列表
         * @param role
         */
        getRoleAppList: function(role) {
            var _self = this
            var requestUrl = VUE_UTIL.buildRequestUrl('/admin/role/queryAppList', {
                roleId: role.id,
            })
            VUE_UTIL.getAxiosInstance().get(requestUrl)
                .then(function(response){
                    _self.roleAppList = response.data.data
                })
        },
        /**
         * 获取角色权限列表
         * @param role
         */
        getRoleFunList: function(role) {
            var _self = this
            var requestUrl = VUE_UTIL.buildRequestUrl('/admin/role/queryFunList', {
                roleId: role.id,
            })
            VUE_UTIL.getAxiosInstance().get(requestUrl)
                .then(function(response){
                    _self.roleFunList = response.data.data
                    // 转换管理数据范围
                    for(var i=0; i<_self.roleFunList.length; i++) {
                        if(_self.roleFunList[i].operateRang) {
                            switch (_self.roleFunList[i].operateRang) {
                                case 0:
                                    _self.roleFunList[i].operateRang = []
                                    break
                                case 1:
                                    _self.roleFunList[i].operateRang = [1]
                                    break
                                case 2:
                                    _self.roleFunList[i].operateRang = [2]
                                    break
                                case 3:
                                    _self.roleFunList[i].operateRang = [1,2]
                                    break
                                case 4:
                                    _self.roleFunList[i].operateRang = [4]
                                    break
                                case 5:
                                    _self.roleFunList[i].operateRang = [1,4]
                                    break
                                case 6:
                                    _self.roleFunList[i].operateRang = [2,4]
                                    break
                                case 7:
                                    _self.roleFunList[i].operateRang = [1,2,4]
                                    break
                                case 8:
                                    _self.roleFunList[i].operateRang = [8]
                                    break
                                case 9:
                                    _self.roleFunList[i].operateRang = [1,8]
                                    break
                                case 10:
                                    _self.roleFunList[i].operateRang = [2,8]
                                    break
                                case 11:
                                    _self.roleFunList[i].operateRang = [1,2,8]
                                    break
                                case 12:
                                    _self.roleFunList[i].operateRang = [4,8]
                                    break
                                case 13:
                                    _self.roleFunList[i].operateRang = [1,4,8]
                                    break
                                case 14:
                                    _self.roleFunList[i].operateRang = [2,4,8]
                                    break
                                case 15:
                                    _self.roleFunList[i].operateRang = [1,2,4,8]
                                    break
                            }
                        }
                    }
                })
        },
        /**
         * 添加角色
         */
        addRole: function() {
            var _self = this
            VUE_UTIL.getAxiosInstance().post("/admin/role/addOrUpdate",VUE_UTIL.buildPostFormData(_self.addRoleData))
            .then(function(response){
                _self.showAddRoleModal = false;
                layer.msg(response.data.msg, {time: 1000});
                _self.getRoleList();
            })
        },

        /**
         * 添加成员
         */
        addMember: function() {
            var _self = this
            _self.selectedMembers = []
            _self.employees = []
            _self.checkedMembers = []
            _self.employeeSearchKey = ''
            if(VUE_UTIL.isEmpty(_self.activeRole)){
                layer.msg('请选选中一个角色', {time: 1000});
                return false
            }
            _self.showAddMemberModal = true;
        },
        editRole: function(role) {
            this.editRoleData = {
                id: role.id,
                name: role.name,
                type: role.type,
                description: role.description
            }
            this.showEditRoleModal = true
        },
        // 查询公司成员
        queryEmployees: function() {
            var _self = this
            var requestUrl = VUE_UTIL.buildRequestUrl("/basedata/employee/queryListByCurrentCompany", {searchKey: this.employeeSearchKey});
            VUE_UTIL.getAxiosInstance().get(requestUrl)
            .then(function(response){
                _self.employees = response.data.data;
            })
        },

        // 获取组织架构树形
        // getDepartments: function() {
        //     var _self = this
        //     VUE_UTIL.getAxiosInstance().post("/basedata/department/queryAllListJSON",VUE_UTIL.buildPostFormData(this.departmentsFilterParameters))
        //         .then(function(response){
        //             // 组织架构json
        //             _self.departments = _self.transFormatToTree(response.data.data);
        //             var departmentTreeRender = document.getElementsByClassName("department-container")[0];
        //             departmentTreeRender.innerHTML = _self.buildDepartmentTree(_self.departments, true);
        //         })
        // },
        // 渲染组织架构树形
        // buildDepartmentTree: function(departmentsJson, flag) {
        //     var _html = "";
        //     if (flag) {
        //         _html += "<ul class='treeNode'>";
        //     } else {
        //         _html += "<ul class='treeNode hidden'>";
        //     }
        //     for (var i = 0; i < departmentsJson.length; i ++) {
        //         if(departmentsJson[i].children && departmentsJson[i].children.length > 0) {
        //             _html += "<li data-id='" + departmentsJson[i].id +"' data-departName='" + departmentsJson[i].name +"' class='hasChildren department'><span class='unFoldBtn'>+</span>" + departmentsJson[i].name + "</li>";
        //             _html += "<li>";
        //             _html += this.buildDepartmentTree(departmentsJson[i].children, false)
        //             _html += "</li>";
        //         } else {
        //             _html +=    "<li data-id='" + departmentsJson[i].id +"' class='department' data-departName='" + departmentsJson[i].name + "' ><span></span>" + departmentsJson[i].name + "</li>";
        //         }
        //     }
        //     _html += "</ul>";
        //     return _html;
        // },
        /**
         * 删除角色
         * @param role
         */
        deleteRole: function(role) {
            var _self = this
            layer.alert('是否删除该角色？', {
                title: '提示信息',
                btn: ['取消', '确认'],
                btn1: function (index) {
                    layer.close(index)
                },
                btn2: function () {
                    var postData = {
                        id: role.id
                    };
                    VUE_UTIL.getAxiosInstance().post("/admin/role/delete",VUE_UTIL.buildPostFormData(postData))
                        .then(function(response){
                            layer.msg(response.data.msg, {time: 1000});
                            _self.getRoleList();
                        })
                }
            })
        },
        /**
         * 设置App权限
         * @param roleApp
         */
        setApp: function(roleApp) {
            var _self = this
            if(roleApp.status == 0) {
                layer.msg('请先启用该应用', {time: 1000});
                return false
            }
            _self.selectedRoleApp = roleApp
            var requestUrl = VUE_UTIL.buildRequestUrl("/admin/role/appPermissionTree",{
                appMetaId: roleApp.appMetaId,
            });
            _self.permissionIds = []
            VUE_UTIL.getAxiosInstance().get(requestUrl)
                .then(function(response){
                    if(response.data){
                        _self.activeAppPermissionTree = response.data.data
                        _self.showSetRoleAppPermissionModal = true
                        VUE_UTIL.getAxiosInstance().get(VUE_UTIL.buildRequestUrl("/admin/role/queryPermissionRels", {
                            roleId: _self.activeRole.id,
                            appMetaId: _self.selectedRoleApp.appMetaId,
                        }))
                            .then(function(response){
                                var permissionIds = []
                                var checkBoxArr = document.getElementsByClassName("permission-checkbox")
                                for(var i = 0; i< checkBoxArr.length; i++) {
                                    checkBoxArr[i].checked = false
                                }
                                if(response.data.data && response.data.data.length > 0) {
                                    for(var i = 0; i< response.data.data.length; i++) {
                                        permissionIds.push(response.data.data[i].permissionMetaId)
                                    }
                                    _self.permissionIds = permissionIds
                                    for(var i = 0; i< checkBoxArr.length; i++) {
                                        for(var j = 0; j< permissionIds.length; j++) {
                                            if(checkBoxArr[i].value == permissionIds[j]) {
                                                checkBoxArr[i].checked = true
                                            }
                                        }
                                    }
                                }
                                console.log(_self.permissionIds)
                            })
                    }
                })
        },
        /**
         * 获取permission id数组
         * @param appPermissionTree
         */
        buildPermissionIdArr: function(appPermissionTree, arr) {
            var permissionIds
            if(arr) {
                permissionIds = arr
            } else {
                permissionIds = []
            }
            for(var i = 0; i < appPermissionTree.length; i++) {
                permissionIds.push(appPermissionTree[i].id)
                if(appPermissionTree[i].hasChildren && appPermissionTree[i].children.length > 0) {
                    permissionIds.concat(this.buildPermissionIdArr(appPermissionTree[i].children, permissionIds))
                }
            }
            return permissionIds
        },
        /**
         * 保存权限设置
         */
        saveRoleAppPermission: function() {
            this.showSetRoleAppPermissionModal = false
            var _self = this
            var permissionIds = []
            var checkBoxArr = document.getElementsByClassName("permission-checkbox")
            for(var i = 0; i< checkBoxArr.length; i++) {
                if(checkBoxArr[i].checked){
                    permissionIds.push(checkBoxArr[i].value)
                }
            }
            var postData = {
                roleId: _self.activeRole.id,
                appMetaId: _self.selectedRoleApp.appMetaId,
                permissionIds: permissionIds,
            }
            axios.post("/admin/role/setPermissions",postData).then(function(response){
                if (response.data.success == true){
                    layer.msg('修改成功', {time: 1000})
                    _self.getRoleAppList(_self.activeRole)
                } else {
                    layer.msg('修改失败', {time: 1000})
                }
            })
        },
        /**
         * 切换启用状态
         * @param roleApp
         */
        changeStatus: function(roleApp) {
            var _self = this
            var postData = {
                id: roleApp.id,
                on: roleApp.status,
            }
            VUE_UTIL.getAxiosInstance().post("/admin/role/appOnOff",VUE_UTIL.buildPostFormData(postData))
                .then(function(response){
                    if (response.data.success == true){
                        layer.msg('修改成功', {time: 1000})
                        _self.getRoleAppList(_self.activeRole)
                    } else {
                        layer.msg('修改失败', {time: 1000})
                    }
                })
        },
        /**
         * 保存数据权限修改
         */
        saveChange: function(){
            var postData = []
            var _self = this
            for(var i = 0; i< this.roleFunList.length; i++) {
                var operateRang = 0
                for(var j = 0; j < this.roleFunList[i].operateRang.length; j++) {
                    operateRang += parseInt(this.roleFunList[i].operateRang[j])
                }
                postData.push({
                    id: this.roleFunList[i].id,
                    queryRang: this.roleFunList[i].queryRang,
                    operateRang: operateRang
                })
            }
            axios.post("/admin/role/updateRoleFun",postData).then(function(response){
                if (response.data.success == true){
                    layer.msg('修改成功', {time: 1000})
                    _self.getRoleFunList(_self.activeRole)
                } else {
                    layer.msg('修改失败', {time: 1000})
                }
            })
        },
        /**
         * 保存角色修改
         */
        saveEditRole: function() {
            var _self = this
            this.editRoleData.name = this.editRoleData.name.trim()
            if(this.editRoleData.name == ""){
                layer.msg('请输入角色名称', {time: 1000})
                return false
            }
            var postData = {
                id: this.editRoleData.id,
                name: this.editRoleData.name,
                type: this.editRoleData.type,
                description: this.editRoleData.description,
            }
            VUE_UTIL.getAxiosInstance().post("/admin/role/addOrUpdate",VUE_UTIL.buildPostFormData(postData))
                .then(function(response){
                    if (response.data.success == true){
                        _self.showEditRoleModal = false
                        layer.msg('修改成功', {time: 1000})
                        _self.getRoleList()
                        _self.activeRoleEditBtns = {}
                    } else {
                        _self.showEditRoleModal = false
                        layer.msg('修改失败', {time: 1000})
                        _self.activeRoleEditBtns = {}
                    }
                })
        },
        /**
         * 保存添加成员
         */
        saveMember: function() {
            var _self = this
            if(this.selectedMembers.length == 0){
                layer.msg('请至少选择一个成员', {time: 1000})
                return false
            }
            var accountIds = [];
            for(var i =0; i< this.selectedMembers.length; i++) {
                accountIds.push(this.selectedMembers[i].id)
            }
            var postData = {
                roleId: this.activeRole.id,
                accountIds: accountIds,
            }
            
            axios.post("/admin/role/addRoleMember",postData).then(function(response){
                if (response.data.success == true){
                    _self.showAddMemberModal = false
                    layer.msg('添加成功', {time: 1000})
                    _self.getRoleMemebers(_self.activeRole)
                } else {
                    _self.showAddMemberModal = false
                    layer.msg('添加失败', {time: 1000})
                }
            })
        },
        /**
         * 将数据转为树形结构
         * @param data
         */
        transFormatToTree: function(data) {
            var obj = {};
            for (var i = 0; i < data.length; i++) {
                if(!data[i].id){
                    return false
                }
                var key = data[i]['id'];
                obj[key] = {
                    'Name': data[i]['name'].toString(),
                    'ID': data[i]['id'].toString(),
                    'ParentID': data[i]['parentId'].toString()
                }
            }
            var resultObj = convert(obj, 0) //根id为0
            function convert(source, rootpid) {
                var tmp = {}, parent, n;
                for (n in source) {
                    var item = source[n];
                    if (item.ID == item.ParentID) {
                        parent = item.ID;
                    }
                    if (!tmp[item.ID]) {
                        tmp[item.ID] = {};
                    }
                    tmp[item.ID].name = item.Name;
                    tmp[item.ID].id = item.ID;
                    if (!("children" in tmp[item.ID])) tmp[item.ID].children = [];

                    if (item.ID!= item.ParentID) {
                        if (tmp[item.ParentID]) {
                            tmp[item.ParentID].children.push(tmp[item.ID]);
                        }
                        else {
                            tmp[item.ParentID] = {
                                children: [tmp[item.ID]]
                            };
                        }
                    }
                }
                return tmp[rootpid];
            }
            return resultObj.children
        },
        /**
         * 添加到已选择成员
         */
        addToSelectedMembers: function() {
            
            for (var i = 0; i< this.checkedMembers.length; i++) {
                var flag = true
                for (var j = 0; j< this.selectedMembers.length; j++) {
                    if(this.selectedMembers[j].id == this.checkedMembers[i].id) {
                        flag = false
                    }
                }
                if (flag) {
                    this.selectedMembers.push(this.checkedMembers[i]);
                }
            }
            
        },
        // 添加到已勾选member
        addToCheckedMembers: function(employee) {
            
            if(event.target.checked) {
                this.checkedMembers.push({
                    id: employee.id,
                    name: employee.employeeName
                })
            } else {
                for(var i =0; i< this.checkedMembers.length; i++) {
                    if(this.checkedMembers[i].id == employee.id) {
                        this.checkedMembers.splice(i, 1)
                    }
                }
            }

        },
        /**
         * 从已选成员中删除
         * @param member
         */
        removeFromSelected: function(member){
            for(var i=0;i<this.selectedMembers.length; i++){
                if(member.id = this.selectedMembers[i].id) {
                    this.selectedMembers.splice(i,1);
                    break
                }
            }
            var inputs = document.querySelectorAll("input.employee-checkbox");
            for(var i=0; i<inputs.length; i++) {
                if(inputs[i].getAttribute("data-id") == member.id){
                    inputs[i].checked = false
                }
            }
        },

        selectAllMembers: function() {
            var inputs = document.querySelectorAll("input.member-checkbox");
            if (event.target.checked) {
                for(var i=0; i<inputs.length; i++) {
                    inputs[i].checked = true
                }
                this.selectedRemoveMembers = this.roleMembersPaging.records
            } else {
                for(var i=0; i<inputs.length; i++) {
                    inputs[i].checked = false
                }
                this.selectedRemoveMembers = []
            }

        },
        addToRemoveMembers: function(member) {
            if (event.target.checked) {
                this.selectedRemoveMembers.push(member)
            } else {
                for (var i = 0; i < this.selectedRemoveMembers.length; i++) {
                    if (this.selectedRemoveMembers[i].accountId == member.accountId) {
                        this.selectedRemoveMembers.splice(i, 1);
                        break
                    }
                }
            }
            console.log(this.selectedRemoveMembers)
        },
        removeMember: function() {
            var _self = this
            if (this.selectedRemoveMembers.length == 0) {
                layer.msg('请至少选中一个账号', {time: 1000})
                return false
            }
            var accountIds = []
            for (var i = 0; i< this.selectedRemoveMembers.length; i++) {
                accountIds.push(this.selectedRemoveMembers[i].accountId)
            }
            layer.confirm('确定要从当前选择角色中删除选中账号?', function (index) {
                layer.close(index);
                axios.post("/admin/role/deleteMember",accountIds).then(function(response){
                    if (response.data.success == true){
                        layer.msg('删除成功', {time: 1000})
                        _self.getRoleMemebers(_self.activeRole)
                    } else {
                        layer.msg('删除失败', {time: 1000})
                    }
                })
            });
        }
    },
})